package ws;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.cachopoid.vo.ComentarioVO;
import com.cachopoid.vo.EventoVO;

public class JSONManager {
	
	 public static JSONObject getJSONfromURL(String url,Object object){
	     InputStream is = null;
	     String result = "";
	     JSONObject json = null;
	      try{
	         HttpClient httpclient = new DefaultHttpClient();
	         HttpPost httppost = new HttpPost(url);
	       //A�ADIR PARAMETROS
	         List<NameValuePair> params = new ArrayList<NameValuePair>();
	         params.add(new BasicNameValuePair("desdeapp","true"));
	         
	         //Si es un objeto Comentario, hacemos el Cast
	         if(object!=null && object.getClass()==com.cachopoid.vo.ComentarioVO.class){
	        	 ComentarioVO comentario = (ComentarioVO) object;
	        	 params.add(new BasicNameValuePair("idCachopo",comentario.getIdCachopo().toString()));
	         }
	         
	         //Si es un objeto Evento, hacemos el Cast
	         if(object!=null && object.getClass()==com.cachopoid.vo.EventoVO.class){
	        	 EventoVO evento = (EventoVO) object;
	        	 params.add(new BasicNameValuePair("idCachopo",evento.getIdCachopo().toString()));
	         }
	         
	         /*Una vez añadidos los parametros actualizamos la entidad de httppost, esto quiere decir en pocas palabras 
	          anexamos los parametros al objeto para que al enviarse al servidor envien los datos que hemos añadido*/
	         httppost.setEntity(new UrlEncodedFormEntity(params));

	         
	         HttpResponse response = httpclient.execute(httppost);
	         HttpEntity entity = response.getEntity();
	         is = entity.getContent();
	     }catch(Exception e){}

	      try{
	         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	         StringBuilder sb = new StringBuilder();
	         String line = null;
	         while ((line = reader.readLine()) != null) {
	             sb.append(line + "\n");
	         }
	         is.close();
	         result=sb.toString();
	     } catch(Exception e){}

	     try{
	         json = new JSONObject(result);
	     }catch(JSONException e){}

	      return json;
	 }
}
